package com.charon.common.listener;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Properties;
import java.util.Timer;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.charon.common.task.SongListTask;

/**
 * @ClassName：TimerListener.java
 * @Description: Servlet启动监听器，启动时启动项目内的推荐歌单爬取任务
 * @Author charon [248135724@qq.com]
 * @Date:   2018年10月30日 下午9:05:06 
 * @version V1.0 
 */
public class TimerListener implements ServletContextListener{

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		 WebApplicationContext springContext = WebApplicationContextUtils
	                .getWebApplicationContext(sce.getServletContext());
		 //启动主监测任务
		 //startTask(springContext);
		 System.out.println("推荐歌单加载任务开始");
	}

	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		
	}
	
	
	private void startTask(WebApplicationContext springContext){
        //获取实时数据监测间隔时间
        InputStream is = this.getClass().getResourceAsStream(
                "/charon.properties");
        Properties properties = new Properties();
        try 
        {
            properties.load(is);
        } 
        catch (IOException e) 
        {
            System.out.println("properties文件读取失败！");
            e.printStackTrace();
        }
        String secondStr = properties.getProperty("song-list-recommend-interval");
        //好眠
        int second = Integer.parseInt(secondStr);
        
        System.out.println(second);
        Timer timer=new Timer();
        //推荐歌单加载功能，一天加载一次
        SongListTask task = new SongListTask(springContext);
        Date date=new Date();
        timer.schedule(task, date,second);
	}

}
